package utils;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * Created by liyuhang on 2019-09-20.
 */
public class FileDowloadUtils {

    /***
     * 文件下载工具类
     * @param response
     * @param inputStream
     * @param fileName
     * @throws IOException
     */
    public static void dowloadFile(HttpServletResponse response, FileInputStream inputStream, String fileName) throws IOException {
        response.reset();
        // 设置response的Header
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        response.setHeader("content-disposition", "attachment;filename="
                + new String(fileName.getBytes("UTF-8"),"ISO8859_1"));
//        response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes()));
        response.setContentType("application/octet-stream");
        response.addHeader("Content-Length", "" + inputStream.available());
        OutputStream outputStream = response.getOutputStream();
        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
        byte[] b = new byte[1024];
        int len;
        while ((len = inputStream.read(b)) > 0){
            response.getOutputStream().write(b, 0, len);
        }
        inputStream.close();
        response.flushBuffer();
    }
}
